Page({
  data: {
    isTesting: false,
    isGameTesting: false,
    testCompleted: false,
    currentSpeed: 0,
    downloadSpeed: 0,
    uploadSpeed: 0,
    ping: 0,
    jitter: 0,
    speedData: [],
    ctx: null,
    ratingText: '',
    ratingClass: '',
    testType: '',
    isAdConfirmShow: false,
    isAdPlaying: false,
    adProgress: 0,
    adCountdown: 0,
    rewardedVideoAd: null,
    adLoaded: false
  },

  onLoad: function() {
    const app = getApp();
    const platform = app.globalData.platform;
    
    // 创建激励视频广告实例
    if (platform === 'douyin' && typeof tt !== 'undefined') {
      console.log('初始化抖音激励视频广告');
      this.createRewardedVideoAd();
    } else if (platform === 'wechat' && typeof wx !== 'undefined') {
      console.log('初始化微信激励视频广告');
      this.createWechatRewardedVideoAd();
    } else {
      console.log('当前环境不支持激励视频广告，将使用模拟广告');
    }
  },

  createRewardedVideoAd: function() {
    const app = getApp();
    const adUnitId = app.globalData.adConfig.rewardedVideoAdUnitId;
    
    const rewardedVideoAd = tt.createRewardedVideoAd({
      adUnitId: adUnitId
    });

    rewardedVideoAd.onLoad(() => {
      console.log('激励视频广告加载成功');
      this.setData({ adLoaded: true });
    });

    rewardedVideoAd.onError((err) => {
      console.log('激励视频广告加载失败', err);
      // 广告加载失败时，直接允许用户进行测试
      wx.showToast({
        title: '广告加载失败，直接进入测试',
        icon: 'none',
        duration: 2000
      });
      this.setData({ adLoaded: false });
    });

    rewardedVideoAd.onClose((res) => {
      // 用户点击了【关闭广告】按钮
      if (res && res.isEnded) {
        // 正常播放结束，可以下发游戏奖励
        console.log('激励视频广告完成，发放奖励');
        this.startActualGameTest();
      } else {
        // 播放中途退出，不下发游戏奖励
        console.log('激励视频广告取消，不发放奖励');
        wx.showToast({
          title: '需要完整观看广告才能进行测试',
          icon: 'none',
          duration: 2000
        });
      }
    });

    this.setData({ rewardedVideoAd });
  },

  createWechatRewardedVideoAd: function() {
    const app = getApp();
    const adUnitId = app.globalData.adConfig.rewardedVideoAdUnitId;
    
    const rewardedVideoAd = wx.createRewardedVideoAd({
      adUnitId: adUnitId
    });

    rewardedVideoAd.onLoad(() => {
      console.log('激励视频广告加载成功');
      this.setData({ adLoaded: true });
    });

    rewardedVideoAd.onError((err) => {
      console.log('激励视频广告加载失败', err);
      // 广告加载失败时，直接允许用户进行测试
      wx.showToast({
        title: '广告加载失败，直接进入测试',
        icon: 'none',
        duration: 2000
      });
      this.setData({ adLoaded: false });
    });

    rewardedVideoAd.onClose((res) => {
      // 用户点击了【关闭广告】按钮
      if (res && res.isEnded) {
        // 正常播放结束，可以下发游戏奖励
        console.log('激励视频广告完成，发放奖励');
        this.startActualGameTest();
      } else {
        // 播放中途退出，不下发游戏奖励
        console.log('激励视频广告取消，不发放奖励');
        wx.showToast({
          title: '需要完整观看广告才能进行测试',
          icon: 'none',
          duration: 2000
        });
      }
    });

    this.setData({ rewardedVideoAd });
  },

  onReady: function() {
    // 获取canvas上下文用于绘制速度波动图表
    this.setData({
      ctx: wx.createCanvasContext('speedCanvas')
    });
  },

  startTest: function() {
    const that = this;
    let speedData = [];
    let testDuration = 5000; // 测试持续时间5秒
    let interval = 200; // 每200ms更新一次速度
    let iterations = testDuration / interval;
    let count = 0;

    this.setData({
      isTesting: true,
      testCompleted: false,
      currentSpeed: 0,
      speedData: []
    });

    // 模拟网速测试过程
    const testInterval = setInterval(function() {
      count++;
      // 生成随机速度值模拟波动 (1-100 Mbps)
      const speed = Math.floor(Math.random() * 99) + 1;
      speedData.push(speed);

      that.setData({
        currentSpeed: speed,
        speedData: speedData
      });

      // 绘制速度波动图表
      that.drawSpeedChart(speedData);

      // 测试结束
      if (count >= iterations) {
        clearInterval(testInterval);
        // 计算平均速度作为结果
        const avgDownload = (speedData.reduce((a, b) => a + b, 0) / speedData.length).toFixed(2);
        const avgUpload = (avgDownload * 0.5).toFixed(2); // 上传速度为下载的一半
        const ping = Math.floor(Math.random() * 90) + 10; // 延迟10-100ms

        // 网络状况评级逻辑
        let ratingText, ratingClass;
        if (avgDownload >= 50) {
          ratingText = '网络状况：优秀';
          ratingClass = 'rating-excellent';
        } else if (avgDownload >= 20) {
          ratingText = '网络状况：良好';
          ratingClass = 'rating-good';
        } else {
          ratingText = '网络状况：较差';
          ratingClass = 'rating-poor';
        }

        that.setData({
          isTesting: false,
          testCompleted: true,
          downloadSpeed: avgDownload,
          uploadSpeed: avgUpload,
          ping: ping,
          testType: 'normal',
          ratingText: ratingText,
          ratingClass: ratingClass
        });
      }
    }, interval);
  },

  drawSpeedChart: function(data) {
    const ctx = this.data.ctx;
    const canvasWidth = wx.getSystemInfoSync().windowWidth - 40; // 减去边距
    const canvasHeight = 300;
    const padding = 30;
    const graphWidth = canvasWidth - padding * 2;
    const graphHeight = canvasHeight - padding * 2;

    // 清空画布
    ctx.clearRect(0, 0, canvasWidth, canvasHeight);

    // 设置坐标轴样式
    ctx.setStrokeStyle('#cccccc');
    ctx.setLineWidth(1);

    // 绘制坐标轴
    ctx.beginPath();
    ctx.moveTo(padding, padding);
    ctx.lineTo(padding, canvasHeight - padding);
    ctx.lineTo(canvasWidth - padding, canvasHeight - padding);
    ctx.stroke();

    // 绘制速度曲线
    if (data.length > 1) {
      ctx.setStrokeStyle('#07c160');
      ctx.setLineWidth(3);
      ctx.beginPath();

      // 计算每个数据点的坐标
      data.forEach((speed, index) => {
        const x = padding + (index / (data.length - 1)) * graphWidth;
        const y = canvasHeight - padding - (speed / 100) * graphHeight; // 速度最大值100

        if (index === 0) {
          ctx.moveTo(x, y);
        } else {
          ctx.lineTo(x, y);
        }
      });

      ctx.stroke();
    }

    ctx.draw();
  },

  restartTest: function() {
    this.setData({
      testCompleted: false,
      currentSpeed: 0
    });
  },

  calculateJitter: function(pingData) {
    if (pingData.length < 2) return 0;
    let sum = 0;
    for (let i = 1; i < pingData.length; i++) {
      sum += Math.abs(pingData[i] - pingData[i-1]);
    }
    return sum / (pingData.length - 1);
  },

  startGameTest: function() {
    this.setData({ isAdConfirmShow: true });
  },

  confirmAd() {
    this.setData({ isAdConfirmShow: false });
    
    // 获取当前环境
    const isDouyin = tt && tt.createRewardedVideoAd;
    const showToast = isDouyin ? tt.showToast : wx.showToast;
    
    // 检查广告是否加载成功
    if (this.data.rewardedVideoAd && this.data.adLoaded) {
      // 显示激励视频广告
      this.data.rewardedVideoAd.show()
        .catch(err => {
          // 失败重试
          this.data.rewardedVideoAd.load()
            .then(() => this.data.rewardedVideoAd.show())
            .catch(err => {
              console.log('激励视频广告显示失败', err);
              showToast({
                title: '广告加载失败，直接进入测试',
                icon: 'none',
                duration: 2000
              });
              this.startActualGameTest();
            });
        });
    } else {
      // 模拟广告播放过程（仅用于开发测试）
      console.log('使用模拟广告（开发测试用）');
      this.setData({ isAdPlaying: true, adProgress: 0, adCountdown: 5 });
      const adInterval = setInterval(() => {
        const newProgress = this.data.adProgress + 20;
        const newCountdown = this.data.adCountdown - 1;
        if (newProgress >= 100) {
          clearInterval(adInterval);
          this.setData({ isAdPlaying: false });
          this.startActualGameTest();
        } else {
          this.setData({ adProgress: newProgress, adCountdown: newCountdown });
        }
      }, 1000);
    }
  },

  cancelAd() {
    this.setData({ isAdConfirmShow: false });
  },

  skipAd() {
    this.setData({ isAdPlaying: false });
    this.startActualGameTest();
  },

  startActualGameTest() {
    this.setData({
      isGameTesting: true,
      testCompleted: false,
      testType: 'game',
      pingData: [],
      jitter: 0,
      avgPing: 0,
      ratingText: '',
      ratingClass: ''
    });

    const pingData = [];
    let count = 0;
    const totalSamples = 16; // 8秒测试，每0.5秒一次采样
    const interval = setInterval(() => {
      // 生成50-100ms之间的随机ping值，波动较小
      const basePing = 70;
      const 波动 = Math.floor(Math.random() * 10) - 5;
      const ping = Math.max(10, basePing + 波动); // 确保ping不会太低
      pingData.push(ping);
      
      this.setData({
        currentSpeed: ping + ' ms',
        pingData: [...pingData]
      });
      
      count++;
      if (count >= totalSamples) {
        clearInterval(interval);
        this.calculateGameResult(pingData);
      } else {
        this.drawGameSpeedChart();
      }
    }, 500);
  },

  calculateGameResult(pingData) {
    // 计算平均ping和抖动
    const avgPing = (pingData.reduce((a, b) => a + b, 0) / pingData.length).toFixed(0);
    const jitter = this.calculateJitter(pingData).toFixed(1);
    
    // 游戏网络评级
    let ratingText, ratingClass;
    if (avgPing < 50 && jitter < 5) {
      ratingText = '游戏网络：优秀';
      ratingClass = 'rating-excellent';
    } else if (avgPing < 100 && jitter < 10) {
      ratingText = '游戏网络：良好';
      ratingClass = 'rating-good';
    } else {
      ratingText = '游戏网络：较差';
      ratingClass = 'rating-poor';
    }
    
    this.setData({
      isGameTesting: false,
      testCompleted: true,
      ping: avgPing,
      jitter: jitter,
      downloadSpeed: '-',
      uploadSpeed: '-',
      ratingText: ratingText,
      ratingClass: ratingClass
    });
  },

  drawGameSpeedChart() {
    // 可以实现游戏测试时的图表绘制，类似drawSpeedChart
    // 此处省略实现...
  }
})